package main

import (
	"awesomeProject/internal/api"
	"awesomeProject/internal/config"
	"awesomeProject/pkg/database"
	"awesomeProject/pkg/logger"
	"awesomeProject/pkg/migration"
	"fmt"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// 程序的入口

func main() {
	// 初始化配置
	cfg := config.Init()

	// 初始化日志
	logger := logger.InitLogger(&cfg.Log)
	zap.ReplaceGlobals(logger)

	// 初始化数据库
	db := database.InitMySQL(&cfg.Database.MySQL)
	redisClient := database.InitRedis(&cfg.Database.Redis)

	// 执行数据库迁移
	if err := migration.InitDatabase(db); err != nil {
		zap.L().Fatal("Failed to initialize database", zap.Error(err))
	}

	// 测试数据库
	sqlDB, err := db.DB()
	if err != nil {
		zap.L().Fatal("Failed to get sqlDB from db", zap.Error(err))
	}
	defer sqlDB.Close()
	defer redisClient.Close()

	// 初始化gin引擎
	r := gin.Default()

	// 设置路由
	api.SetupRoutes(r, db, cfg)

	// 启动服务
	zap.L().Info("Server is running at", zap.String("port", fmt.Sprintf(":%d", cfg.Server.Port)))
	if err := r.Run(fmt.Sprintf(":%d", cfg.Server.Port)); err != nil {
		zap.L().Fatal("Failed to start server", zap.Error(err))
	}

}
